<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <view class="navbar">
      <view class="back-btn" @click="goBack">
        <text class="iconfont icon-back"></text>
      </view>
      <text class="title">任务详情</text>
      <view class="action-btn" @click="editTask">
        <text class="iconfont icon-edit"></text>
      </view>
    </view>

    <scroll-view class="content" scroll-y>
      <!-- 任务状态和优先级 -->
      <view class="task-header">
        <view class="task-status" :class="`status-${task.status}`">
          {{ getStatusLabel(task.status) }}
        </view>
        <view class="task-priority" :class="`priority-${task.priority}`">
          {{ getPriorityLabel(task.priority) }}
        </view>
      </view>

      <!-- 任务标题 -->
      <view class="task-title">
        {{ task.title }}
      </view>

      <!-- 任务元信息 -->
      <view class="task-meta">
        <!-- 创建时间和更新时间 -->
        <view class="meta-item">
          <text class="meta-label">创建时间：</text>
          <text class="meta-value">{{ formatDateTime(task.createdTime) }}</text>
        </view>
        
        <!-- 截止时间 -->
        <view v-if="task.dueTime" class="meta-item">
          <text class="meta-label">截止时间：</text>
          <text class="meta-value" :class="{ 'overdue': isOverdue }">
            {{ formatDateTime(task.dueTime) }}
            <text v-if="daysUntilDue !== null" class="due-days">{{ daysUntilDue }}</text>
          </text>
        </view>

        <!-- 提醒时间 -->
        <view v-if="task.remindTime" class="meta-item">
          <text class="meta-label">提醒时间：</text>
          <text class="meta-value">{{ formatDateTime(task.remindTime) }}</text>
        </view>

        <!-- 分类功能已移除，后端不支持 -->
      </view>

      <!-- 任务描述 -->
      <view v-if="task.description" class="task-description">
        <text class="section-title">任务描述</text>
        <text class="description-content">{{ task.description }}</text>
      </view>

      <!-- 标签功能已移除，后端不支持 -->

      <!-- 子任务功能已移除，后端不支持 -->

      <!-- 附件功能已移除，后端不支持 -->

      <!-- 评论功能已移除，后端不支持 -->

      <!-- 底部空间 -->
      <view style="height: 200rpx;"></view>
    </scroll-view>

    <!-- 底部操作栏 -->
    <view class="bottom-actions">
      <view class="action-buttons">
        <button 
          class="action-btn primary-btn" 
          @click="changeTaskStatus"
          :class="{ 'disabled': isLoading }"
          :disabled="isLoading"
        >
          {{ getNextStatusButtonLabel() }}
        </button>
        
        <button 
          class="action-btn secondary-btn" 
          @click="showDeleteConfirm"
          :class="{ 'disabled': isLoading }"
          :disabled="isLoading"
        >
          删除任务
        </button>
      </view>
      
      <!-- 评论输入框已移除，后端不支持评论功能 -->
    </view>

    <!-- 子任务弹窗已移除，后端不支持子任务功能 -->

    <!-- 加载状态 -->
    <view v-if="isLoading" class="loading-mask">
      <view class="loading-spinner"></view>
      <text class="loading-text">处理中...</text>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import taskApi from '../../api/task';
import { showToast, confirm, showLoading, hideLoading } from '../../utils/uni';
// 导入uni-popup组件
import uniPopup from '@dcloudio/uni-ui/lib/uni-popup/uni-popup.vue';

const router = useRouter();
const route = useRoute();

// 响应式数据
const task = ref({
  id: '',
  userId: '',
  title: '',
  description: '',
  type: '',
  startTime: null,
  endTime: null,
  status: 0, // 0-未开始, 1-已完成
  priority: 'medium',
  duration: 0,
  completionRate: 0,
  energyReward: 0,
  createTime: '',
  updateTime: ''
});

const isLoading = ref(false);
const newComment = ref('');
const isCommentFocused = ref(false);
const subtaskPopup = ref(null);
const newSubtaskTitle = ref('');

// 计算属性
// 计算属性
const isOverdue = computed(() => {
  if (!task.value.endTime || task.value.status === 1) return false;
  return new Date(task.value.endTime) < new Date();
});

const daysUntilDue = computed(() => {
  if (!task.value.endTime || task.value.status === 1) return null;
  
  const now = new Date();
  const due = new Date(task.value.endTime);
  const diffTime = due - now;
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
  
  if (diffDays === 0) {
    return '(今天)';
  } else if (diffDays === 1) {
    return '(明天)';
  } else if (diffDays > 1) {
    return `(${diffDays}天后)`;
  } else {
    return `(已过期${Math.abs(diffDays)}天)`;
  }
});

// 方法
const loadTaskDetail = async () => {
  const taskId = route.params.id;
  if (!taskId) {
    showToast('任务ID不存在', 'error');
    router.back();
    return;
  }
  
  isLoading.value = true;
  
  try {
    // 由于后端没有单独的获取任务详情接口，可以先获取用户所有任务再过滤
    const userId = uni.getStorageSync('userId') || '1';
    const res = await taskApi.getUserTasks(userId);
    const taskData = res.data.find(t => t.id === taskId);
    
    if (!taskData) {
      showToast('任务不存在', 'error');
      router.back();
      return;
    }
    
    task.value = taskData;
  } catch (error) {
    showToast('加载任务详情失败', 'error');
    console.error('Failed to load task detail:', error);
    router.back();
  } finally {
    isLoading.value = false;
  }
};

const getStatusLabel = (status) => {
  const statusMap = {
    0: '未开始',
    1: '已完成'
  };
  return statusMap[status] || '未知';
};

const getPriorityLabel = (priority) => {
  const priorityMap = {
    high: '高优先级',
    medium: '中优先级',
    low: '低优先级'
  };
  return priorityMap[priority] || '普通';
};

const formatDateTime = (dateTime) => {
  if (!dateTime) return '';
  
  const date = new Date(dateTime);
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}`;
};

const formatRelativeTime = (dateTime) => {
  if (!dateTime) return '';
  
  const now = new Date();
  const date = new Date(dateTime);
  const diffTime = now - date;
  const diffMinutes = Math.floor(diffTime / (1000 * 60));
  const diffHours = Math.floor(diffTime / (1000 * 60 * 60));
  const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
  
  if (diffMinutes < 1) return '刚刚';
  if (diffMinutes < 60) return `${diffMinutes}分钟前`;
  if (diffHours < 24) return `${diffHours}小时前`;
  if (diffDays < 7) return `${diffDays}天前`;
  
  return formatDateTime(dateTime);
};

const getNextStatusButtonLabel = () => {
  switch (task.value.status) {
    case 0:
      return '标记为完成';
    case 1:
      return '重新激活';
    default:
      return '更新状态';
  }
};

const changeTaskStatus = async () => {
  const newStatus = task.value.status === 1 ? 0 : 1;
  
  isLoading.value = true;
  
  try {
    await taskApi.completeTask(task.value.id);
    task.value.status = newStatus;
    showToast(newStatus === 1 ? '任务已完成' : '任务已重新激活');
  } catch (error) {
    showToast('更新任务状态失败', 'error');
    console.error('Failed to update task status:', error);
  } finally {
    isLoading.value = false;
  }
};

const showDeleteConfirm = async () => {
  const confirmed = await confirm('确定要删除这个任务吗？删除后无法恢复。');
  if (!confirmed) return;
  
  isLoading.value = true;
  
  try {
    await taskApi.deleteTask(task.value.id);
    showToast('任务已删除');
    // 延迟返回，让用户看到提示
    setTimeout(() => {
      router.back();
    }, 1500);
  } catch (error) {
    showToast('删除任务失败', 'error');
    console.error('Failed to delete task:', error);
  } finally {
    isLoading.value = false;
  }
};

const editTask = () => {
  router.push(`/pages/task/taskEdit?id=${task.value.id}`);
};

const goBack = () => {
  router.back();
};

const submitComment = async () => {
  if (!newComment.value.trim()) return;
  
  isLoading.value = true;
  
  try {
    const res = await taskApi.addTaskComment(task.value.id, {
      content: newComment.value.trim()
    });
    
    // 添加到评论列表
    if (!task.value.comments) {
      task.value.comments = [];
    }
    task.value.comments.push({
      id: res.data?.id,
      content: newComment.value.trim(),
      createdTime: new Date().toISOString(),
      user: {
        id: res.data?.userId,
        name: res.data?.userName || '我'
      }
    });
    
    newComment.value = '';
    isCommentFocused.value = false;
    showToast('评论已发送');
  } catch (error) {
    showToast('发送评论失败', 'error');
    console.error('Failed to submit comment:', error);
  } finally {
    isLoading.value = false;
  }
};

const onCommentFocus = () => {
  isCommentFocused.value = true;
};

const addSubtask = () => {
  if (!task.value.subtasks) {
    task.value.subtasks = [];
  }
  subtaskPopup.value?.open();
};

const closeSubtaskPopup = () => {
  subtaskPopup.value?.close();
  newSubtaskTitle.value = '';
};

const confirmAddSubtask = async () => {
  if (!newSubtaskTitle.value.trim()) return;
  
  try {
    const subtaskData = {
      title: newSubtaskTitle.value.trim(),
      completed: false
    };
    
    // 调用API添加子任务
    const res = await taskApi.addTaskSubtask(task.value.id, subtaskData);
    
    // 更新本地子任务列表
    task.value.subtasks.push({
      id: res.data?.id,
      ...subtaskData
    });
    
    closeSubtaskPopup();
    showToast('子任务已添加');
  } catch (error) {
    // 如果API调用失败，本地模拟添加
    task.value.subtasks.push({
      id: `temp-${Date.now()}`,
      title: newSubtaskTitle.value.trim(),
      completed: false
    });
    
    closeSubtaskPopup();
    showToast('子任务已添加（离线模式）', 'info');
    console.error('Failed to add subtask:', error);
  }
};

const toggleSubtaskStatus = async (subtask) => {
  const newStatus = !subtask.completed;
  
  try {
    // 如果有ID，调用API更新
    if (subtask.id && !subtask.id.startsWith('temp-')) {
      await taskApi.updateTaskSubtask(task.value.id, subtask.id, { completed: newStatus });
    }
    
    // 更新本地状态
    subtask.completed = newStatus;
  } catch (error) {
    // 回滚状态
    subtask.completed = !newStatus;
    showToast('更新子任务状态失败', 'error');
    console.error('Failed to toggle subtask status:', error);
  }
};

const removeSubtask = async (subtaskId) => {
  const confirmed = await confirm('确定要删除这个子任务吗？');
  if (!confirmed) return;
  
  try {
    // 如果有正式ID，调用API删除
    if (subtaskId && !subtaskId.toString().startsWith('temp-')) {
      await taskApi.deleteTaskSubtask(task.value.id, subtaskId);
    }
    
    // 从本地列表中移除
    task.value.subtasks = task.value.subtasks.filter(st => {
      return st.id !== subtaskId;
    });
    
    showToast('子任务已删除');
  } catch (error) {
    showToast('删除子任务失败', 'error');
    console.error('Failed to remove subtask:', error);
  }
};

const openAttachment = (attachment) => {
  // 处理附件打开逻辑
  if (attachment.url) {
    // 根据文件类型选择不同的打开方式
    if (attachment.type === 'image') {
      // 图片预览
      const urls = task.value.attachments
        .filter(a => a.type === 'image' && a.url)
        .map(a => a.url);
      
      uni.previewImage({
        urls: urls,
        current: attachment.url
      });
    } else {
      // 其他文件类型使用系统打开
      uni.downloadFile({
        url: attachment.url,
        success: (res) => {
          if (res.statusCode === 200) {
            uni.openDocument({
              filePath: res.tempFilePath,
              showMenu: true,
              fail: (err) => {
                showToast('无法打开文件', 'error');
                console.error('Failed to open document:', err);
              }
            });
          }
        },
        fail: (err) => {
          showToast('下载文件失败', 'error');
          console.error('Failed to download file:', err);
        }
      });
    }
  } else {
    showToast('附件路径无效', 'error');
  }
};

// 监听路由参数变化
watch(() => route.params.id, () => {
  loadTaskDetail();
});

// 生命周期
onMounted(() => {
  loadTaskDetail();
});
</script>

<style scoped>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.navbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 100rpx;
  padding: 0 30rpx;
  background-color: #fff;
  position: sticky;
  top: 0;
  z-index: 10;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.back-btn,
.action-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-btn .iconfont,
.action-btn .iconfont {
  font-size: 36rpx;
  color: #333;
}

.navbar .title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.content {
  padding-bottom: 200rpx;
}

.task-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  background-color: #fff;
  border-bottom: 2rpx solid #f0f0f0;
}

.task-status {
  padding: 8rpx 24rpx;
  border-radius: 60rpx;
  font-size: 28rpx;
  font-weight: bold;
}

.status-active {
  background-color: #e3f2fd;
  color: #1976d2;
}

.status-completed {
  background-color: #e8f5e8;
  color: #43a047;
}

.status-expired {
  background-color: #ffebee;
  color: #c62828;
}

.status-draft {
  background-color: #f5f5f5;
  color: #757575;
}

.task-priority {
  padding: 8rpx 24rpx;
  border-radius: 60rpx;
  font-size: 28rpx;
  font-weight: bold;
}

.priority-high {
  background-color: #ffebee;
  color: #c62828;
}

.priority-medium {
  background-color: #fff8e1;
  color: #ff8f00;
}

.priority-low {
  background-color: #e8f5e8;
  color: #43a047;
}

.task-title {
  padding: 30rpx;
  background-color: #fff;
  font-size: 40rpx;
  font-weight: bold;
  color: #333;
  line-height: 1.5;
}

.task-meta {
  padding: 30rpx;
  background-color: #fff;
  margin-top: 20rpx;
}

.meta-item {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.meta-item:last-child {
  margin-bottom: 0;
}

.meta-label {
  font-size: 28rpx;
  color: #666;
  margin-right: 16rpx;
  width: 120rpx;
}

.meta-value {
  font-size: 28rpx;
  color: #333;
  flex: 1;
}

.meta-value.overdue {
  color: #c62828;
}

.due-days {
  margin-left: 10rpx;
  font-size: 24rpx;
  color: #999;
}

.category-tag {
  padding: 6rpx 20rpx;
  border-radius: 16rpx;
  font-size: 26rpx;
  color: #fff;
}

.task-description,
.task-tags,
.subtasks-section,
.task-attachments,
.task-comments {
  margin-top: 20rpx;
  padding: 30rpx;
  background-color: #fff;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.description-content {
  font-size: 28rpx;
  color: #666;
  line-height: 1.6;
  white-space: pre-wrap;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 12rpx;
}

.tag {
  padding: 8rpx 20rpx;
  background-color: #f0f0f0;
  border-radius: 60rpx;
  font-size: 26rpx;
  color: #666;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20rpx;
}

.section-action {
  font-size: 28rpx;
  color: #4a90e2;
}

.section-count {
  font-size: 28rpx;
  color: #999;
  font-weight: normal;
}

.subtask-item {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 2rpx solid #f0f0f0;
}

.subtask-item:last-child {
  border-bottom: none;
}

.checkbox-wrapper {
  margin-right: 20rpx;
}

.checkbox {
  width: 40rpx;
  height: 40rpx;
  border: 3rpx solid #ddd;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.checkbox.checked {
  background-color: #4a90e2;
  border-color: #4a90e2;
}

.checkbox.checked .iconfont {
  color: #fff;
  font-size: 24rpx;
}

.subtask-title {
  flex: 1;
  font-size: 28rpx;
  color: #333;
}

.subtask-title.line-through {
  text-decoration: line-through;
  color: #999;
}

.subtask-item .icon-delete {
  font-size: 28rpx;
  color: #ff6b6b;
}

.empty-subtasks {
  padding: 40rpx 0;
  text-align: center;
  font-size: 28rpx;
  color: #999;
}

.subtask-progress {
  margin-top: 30rpx;
}

.progress-bar {
  width: 100%;
  height: 12rpx;
  background-color: #f0f0f0;
  border-radius: 6rpx;
  overflow: hidden;
  margin-bottom: 10rpx;
}

.progress-fill {
  height: 100%;
  background-color: #4a90e2;
  border-radius: 6rpx;
  transition: width 0.3s;
}

.progress-text {
  font-size: 24rpx;
  color: #666;
  text-align: right;
}

.attachments-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20rpx;
}

.attachment-item {
  padding: 20rpx;
  background-color: #f5f5f5;
  border-radius: 16rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 140rpx;
}

.attachment-item .iconfont {
  font-size: 60rpx;
  color: #4a90e2;
  margin-bottom: 10rpx;
}

.attachment-name {
  font-size: 24rpx;
  color: #333;
  margin-bottom: 8rpx;
  text-align: center;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.attachment-size {
  font-size: 20rpx;
  color: #999;
}

.comments-container {
  margin-top: 20rpx;
}

.comment-item {
  display: flex;
  margin-bottom: 30rpx;
}

.comment-item:last-child {
  margin-bottom: 0;
}

.comment-avatar {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  background-color: #4a90e2;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 30rpx;
  margin-right: 20rpx;
  flex-shrink: 0;
}

.comment-content {
  flex: 1;
}

.comment-header {
  display: flex;
  align-items: center;
  margin-bottom: 8rpx;
}

.comment-author {
  font-size: 26rpx;
  font-weight: bold;
  color: #333;
  margin-right: 16rpx;
}

.comment-time {
  font-size: 22rpx;
  color: #999;
}

.comment-text {
  font-size: 28rpx;
  color: #666;
  line-height: 1.5;
}

.empty-comments {
  padding: 40rpx 0;
  text-align: center;
  font-size: 28rpx;
  color: #999;
}

.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  border-top: 2rpx solid #f0f0f0;
  padding: 20rpx 30rpx;
  z-index: 100;
}

.action-buttons {
  display: flex;
  gap: 20rpx;
  margin-bottom: 20rpx;
}

.action-btn {
  flex: 1;
  height: 90rpx;
  line-height: 90rpx;
  font-size: 32rpx;
  border-radius: 45rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.primary-btn {
  background-color: #4a90e2;
  color: #fff;
}

.secondary-btn {
  background-color: #fff;
  color: #ff6b6b;
  border: 2rpx solid #ff6b6b;
}

.action-btn.disabled {
  opacity: 0.6;
}

.comment-input-wrapper {
  display: flex;
  align-items: center;
  background-color: #f5f5f5;
  border-radius: 60rpx;
  padding: 0 20rpx;
  height: 80rpx;
}

.comment-input {
  flex: 1;
  height: 100%;
  padding: 0 20rpx;
  font-size: 28rpx;
  color: #333;
  background-color: transparent;
}

.send-comment-btn {
  width: 100rpx;
  height: 60rpx;
  line-height: 60rpx;
  font-size: 28rpx;
  background-color: #4a90e2;
  color: #fff;
  border-radius: 30rpx;
}

.send-comment-btn:disabled {
  background-color: #ccc;
  color: #fff;
}

.popup-content {
  background-color: #fff;
  border-top-left-radius: 30rpx;
  border-top-right-radius: 30rpx;
}

.popup-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 2rpx solid #f0f0f0;
}

.popup-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.popup-close {
  font-size: 40rpx;
  color: #999;
}

.popup-body {
  padding: 30rpx;
}

.subtask-input {
  width: 100%;
  padding: 20rpx;
  font-size: 32rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 16rpx;
  box-sizing: border-box;
}

.popup-actions {
  display: flex;
  padding: 30rpx;
  gap: 20rpx;
}

.popup-actions button {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  font-size: 32rpx;
  border-radius: 40rpx;
}

.cancel-btn {
  background-color: #f5f5f5;
  color: #666;
}

.confirm-btn {
  background-color: #4a90e2;
  color: #fff;
}

.confirm-btn:disabled {
  background-color: #ccc;
  color: #fff;
}

.loading-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 999;
}

.loading-spinner {
  width: 80rpx;
  height: 80rpx;
  border: 8rpx solid #f3f3f3;
  border-top: 8rpx solid #4a90e2;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 20rpx;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  color: #fff;
  font-size: 32rpx;
}
</style>